const http = require('http');
const fs = require('fs');

const server = http.createServer();

server.on('request',function (req,res) {
    let url = req.url;
    if (url === '/') { // 读取 html 
        fs.readFile('./resouce/index.html',function (err,data) {
            if(err){
                res.setHeader('Content-type','text/plain;charset=utf-8');
                res.end('文件读取失败...');
            }else {
                res.setHeader('Content-type','text/html;charset=utf-8');
                res.end(data);
            }
        });
    }else if (url === '/img') {
        fs.readFile('./resouce/lianxiwomen_05.jpg',function (err,data) {
            if(err){
                res.setHeader('Content-type','text/plain;charset=utf-8');
                res.end('文件读取失败...');
            }else {
                res.setHeader('Content-type','image/jpeg');
                res.end(data);
            }
        });
    }else if (url === '/js') {
        fs.readFile('./resouce/main.js',function (err,data) {
            if(err){
                res.setHeader('Content-type','text/plain;charset=utf-8');
                res.end('文件读取失败...');
            }else {
                res.setHeader('Content-type','application/x-javascript;charset=utf-8');
                res.end(data);
            }
        });
    }else if (url === '/txt') {
        fs.readFile('./resouce/plain.txt',function (err,data) {
            if(err){
                res.setHeader('Content-type','text/plain;charset=utf-8');
                res.end('文件读取失败...');
            }else {
                res.setHeader('Content-type','text/plain;charset=utf-8');
                res.end(data);
            }
        });
    }

});

server.listen(3002,function () {
    console.log('server works,running on port 3002');
});